package com.mzy.linear_struct.subject;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: codermzy
 * @Date: 2024/04/13/22:27
 * @Description:
 */
public class 两数之和 {

    // public int[] twoSum(int[] nums, int target) {
    //
    //     Map<Integer, Integer> map = new HashMap<>();
    //     // [2,7,11,15]
    //     for (int i = 0; i < nums.length; i++) {
    //         int diff = target - nums[i];
    //         if (map.containsKey(diff)) {
    //             return new int[]{map.get(diff), i};
    //         }
    //         map.put(nums[i], i);
    //     }
    //     return new int[2];
    // }


    public static void main(String[] args) {
        int[] arr = {2, 7, 11, 15};
        for (int i : new 两数之和().twoSum(arr, 9)) {
            System.out.println(i);
        }
    }

    private int[] twoSum(int[] arr, int target) {
        HashMap<Integer, Integer> map = new HashMap<>();

        // map {{k: 7, v: 1}}


        // 9
        // 9 - 2
        for (int i = 0; i < arr.length; i++) {
            int temp = target - arr[i];
            if(map.get(temp) != null){
                return new int[]{map.get(temp), i};
            }
            // 2,0
            map.put(arr[i], i);
        }

        return new int[2];

    }
}